<template>
  <el-dialog
    :title="isEdit ? '编辑字典数据' : '新增字典数据'"
    v-model="visible"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="字典类型" prop="dictTypeId">
        <el-select v-model="form.dictTypeId" placeholder="请选择字典类型">
          <el-option
            v-for="type in dictTypes"
            :key="type.id"
            :label="type.name"
            :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签名" prop="label">
        <el-input v-model="form.label" />
      </el-form-item>
      <el-form-item label="数据值" prop="value">
        <el-input v-model="form.value" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createDictData, updateDictData } from '@/api/dict'

const props = defineProps({
  modelValue: Boolean,
  dataData: Object,
  dictTypes: Array
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref()
const loading = ref(false)

const form = reactive({
  id: null,
  dictTypeId: null,
  label: '',
  value: '',
  sort: 0,
  description: '',
  status: true
})

const rules = {
  dictTypeId: [
    { required: true, message: '请选择字典类型', trigger: 'change' }
  ],
  label: [
    { required: true, message: '请输入标签名', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入数据值', trigger: 'blur' }
  ]
}

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.dataData && !props.dataData._isAdd)

const resetForm = () => {
  Object.assign(form, {
    id: null,
    dictTypeId: null,
    label: '',
    value: '',
    sort: 0,
    description: '',
    status: true
  })
  formRef.value?.clearValidate()
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (isEdit.value) {
          await updateDictData(form.id, form)
          ElMessage.success('更新成功')
        } else {
          await createDictData(form)
          ElMessage.success('创建成功')
        }
        emit('success')
        handleClose()
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      } finally {
        loading.value = false
      }
    }
  })
}

watch(() => props.dataData, (newVal) => {
  if (newVal) {
    if (newVal._isAdd) {
      // 新增模式，只设置dictTypeId，其他字段保持默认值
      Object.assign(form, {
        id: null,
        dictTypeId: newVal.dictTypeId,
        label: '',
        value: '',
        sort: 0,
        description: '',
        status: true
      })
    } else {
      // 编辑模式，设置所有字段
      Object.assign(form, {
        id: newVal.id,
        dictTypeId: newVal.dictTypeId || newVal.typeCode,
        label: newVal.label,
        value: newVal.value,
        sort: newVal.sort,
        description: newVal.description,
        status: newVal.status
      })
    }
  } else {
    resetForm()
  }
}, { immediate: true })
</script>